<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { UserApi } from '@/api/UserApi.ts'
import type { UserVO, SearchParams } from '@/api/User.ts'
import InfoDialog from './components/InfoDialog.vue'
import UpdateDialog from './components/UpdateDialog.vue'
import DeleteDialog from './components/DeleteDialog.vue'
import { message } from 'ant-design-vue'
import { ReloadOutlined } from '@ant-design/icons-vue'
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    align: 'center',
  },
  {
    title: '账号',
    dataIndex: 'account',
    key: 'account',
    align: 'center',
  },
  {
    title: '昵称',
    dataIndex: 'name',
    key: 'name',
    align: 'center',
  },
  {
    title: '性别',
    key: 'gender',
    dataIndex: 'gender',
    align: 'center',
  },
  {
    title: '邮箱',
    key: 'email',
    dataIndex: 'email',
    align: 'center',
  },
  {
    title: '角色',
    key: 'role',
    dataIndex: 'role',
    align: 'center',
  },
  {
    title: '通过率',
    key: 'passRate',
    dataIndex: 'passRate',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
  },
];

const loading = ref(false)
const tableData = ref<UserVO[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
})

const queryParams = ref<SearchParams>({
  id: null,
  account: null,
  gender: null,
})

const sanitizeParams = (params: SearchParams) => {
  return {
    id: params.id !== null && String(params.id).trim() !== '' ? String(params.id).trim() : null,
    account: params.account !== null && String(params.account).trim() !== '' ? String(params.account).trim() : null,
    gender: params.gender === 0 || params.gender === 1 ? params.gender : null,
  }
}

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      ...sanitizeParams(queryParams.value),
      pageNumber: pagination.current,
      pageSize: pagination.pageSize,
    }
    const data = await UserApi.search(params)
    tableData.value = data?.records || []
    pagination.current = data?.pageNumber || 1
    pagination.pageSize = data?.pageSize || 10
    pagination.total = data?.totalRow || 0
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})

const onSearch = () => {
  pagination.current = 1
  fetchData()
}

const onReset = () => {
  queryParams.value = { id: null, account: null, gender: null }
  pagination.current = 1
  fetchData()
}

const handleTableChange = (pag: any) => {
  pagination.current = pag?.current || 1
  pagination.pageSize = pag?.pageSize || 10
  fetchData()
}

const deleteDialogOpen = ref(false)
const deletingUserId = ref<string | null>(null)
const deletingUserName = ref<string | null>(null)

const onDelete = (id: string) => {
  const user = tableData.value.find(item => item.id === id)
  if (user) {
    deletingUserId.value = user.id
    deletingUserName.value = user.name || user.account
    deleteDialogOpen.value = true
  }
}

const onDeleteDialogOpenChange = (open: boolean) => {
  deleteDialogOpen.value = open
  if (!open) {
    deletingUserId.value = null
    deletingUserName.value = null
  }
}

const onDeleteSuccess = () => {
  deleteDialogOpen.value = false
  deletingUserId.value = null
  deletingUserName.value = null
  fetchData()
}

const getRoleColor = (role: string) => {
  switch (role) {
    case 'ROLE_SUPER_ADMIN':
      return 'volcano'
    case 'ROLE_ADMIN':
      return 'geekblue'
    case 'ROLE_USER':
      return 'green'
    default:
      return 'default'
  }
}

const getRoleLabel = (role: string) => {
  switch (role) {
    case 'ROLE_SUPER_ADMIN':
      return '超级管理员'
    case 'ROLE_ADMIN':
      return '管理员'
    case 'ROLE_USER':
      return '用户'
    default:
      return role
  }
}

const getGenderLabel = (gender: number | null | undefined) => {
  switch (gender) {
    case 0:
      return '男'
    case 1:
      return '女'
    default:
      return ''
  }
}

const formatPassRate = (record: any) => {
  const submit = Number(record?.submit ?? 0)
  const solved = Number(record?.solved ?? 0)
  if (!submit || submit <= 0) return '0.00%'
  const rate = (solved / submit) * 100
  return `${rate.toFixed(2)}%`
}

const router = useRouter()
const drawerOpen = ref(false)
const drawerMode = ref<'view' | 'edit'>('view')
const selectedUser = ref<UserVO | null>(null)

const openDrawer = (mode: 'view' | 'edit', user: UserVO) => {
  drawerMode.value = mode
  selectedUser.value = user
  drawerOpen.value = true
}

const closeDrawer = () => {
  drawerOpen.value = false
  selectedUser.value = null
}

const onUpdateSuccess = () => {
  fetchData() // 刷新数据列表
}

const onEdit = (record: UserVO) => {
  openDrawer('edit', record)
}

const onView = (record: UserVO) => {
  openDrawer('view', record)
}

const onAction = (key: string, record: any) => {
  switch (key) {
    case 'edit':
      onEdit(record)
      break
    case 'view':
      onView(record)
      break
    case 'delete':
      onDelete(record.id)
      break
    default:
      break
  }
}

const onMenuClick = (info: any, record: any) => {
  onAction(String(info?.key ?? ''), record)
}

</script>

<template>
  <div class="w-full">
    <a-card
      title="用户管理"
      class="w-full rounded-lg shadow-sm"
      :bodyStyle="{ padding: '24px' }"
    >
      <!-- 搜索表单 -->
      <div class="mb-6 flex flex-wrap items-center gap-4">
        <div class="flex items-center gap-2">
          <label class="text-sm font-medium text-gray-700 whitespace-nowrap">ID:</label>
          <a-input
            v-model:value="queryParams.id"
            placeholder="输入ID"
            allow-clear
            @pressEnter="onSearch"
            class="w-[200px]"
          />
        </div>

        <div class="flex items-center gap-2">
          <label class="text-sm font-medium text-gray-700 whitespace-nowrap">账号:</label>
          <a-input
            v-model:value="queryParams.account"
            placeholder="输入账号"
            allow-clear
            @pressEnter="onSearch"
            class="w-[200px]"
          />
        </div>

        <div class="flex items-center gap-2">
          <label class="text-sm font-medium text-gray-700 whitespace-nowrap">性别:</label>
          <a-select
            v-model:value="queryParams.gender"
            placeholder="选择性别"
            allow-clear
            class="w-[160px]"
          >
            <a-select-option :value="0">男</a-select-option>
            <a-select-option :value="1">女</a-select-option>
          </a-select>
        </div>

        <div class="flex items-center gap-2">
          <a-button type="primary" @click="onSearch" class="px-6">
            搜索
          </a-button>
          <a-tooltip title="重置">
            <a-button
              @click="onReset"
              :shape="'default'"
              class="w-9 h-9 p-0 flex items-center justify-center"
            >
              <template #icon>
                <ReloadOutlined />
              </template>
            </a-button>
          </a-tooltip>
        </div>
      </div>

      <!-- 用户表格 -->
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        rowKey="id"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showTotal: (total: number) => `共 ${total} 条`
        }"
        @change="handleTableChange"
        :scroll="{ x: 1200 }"
        class="rounded-lg"
        :customRow="(record: any) => ({ class: 'hover:bg-slate-50' })"
        :customHeaderRow="() => ({ class: 'bg-slate-50 border-b-2 border-slate-200' })"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'role'">
            <a-tag :color="getRoleColor(record.role)" class="px-2 py-1 rounded-full text-xs font-medium">
              {{ getRoleLabel(record.role) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'gender'">
            <span class="text-sm font-medium text-gray-700">{{ getGenderLabel(record.gender) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'passRate'">
            <span class="text-sm font-medium text-gray-700">{{ formatPassRate(record) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <a-dropdown :trigger="['click']">
              <a-button type="link" size="small" class="text-blue-600 hover:text-blue-800 font-medium">
                操作
              </a-button>
              <template #overlay>
                <a-menu @click="onMenuClick($event, record)" class="rounded-lg shadow-lg border border-gray-200">
                  <a-menu-item key="edit" class="hover:bg-blue-50 transition-colors">
                    <span class="text-gray-700">修改</span>
                  </a-menu-item>
                  <a-menu-item key="view" class="hover:bg-blue-50 transition-colors">
                    <span class="text-gray-700">查看详情</span>
                  </a-menu-item>
                  <a-menu-divider class="my-1" />
                  <a-menu-item key="delete" class="hover:bg-red-50 transition-colors">
                    <span class="text-red-600">删除</span>
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>

  <a-drawer
    :open="drawerOpen"
    :width="620"
    placement="right"
    destroyOnClose
    @close="closeDrawer"
  >
    <template #title>
      {{ drawerMode === 'view' ? '用户详情' : '修改用户信息' }}
    </template>
    <component
      :is="drawerMode === 'view' ? InfoDialog : UpdateDialog"
      v-if="selectedUser"
      :user="selectedUser"
      @close="closeDrawer"
      @success="onUpdateSuccess"
    />
  </a-drawer>
  <delete-dialog
    :open="deleteDialogOpen"
    :user-id="deletingUserId"
    :user-name="deletingUserName"
    @update:open="onDeleteDialogOpenChange"
    @success="onDeleteSuccess"
  />
</template>

